package com.newfiber.common.core.web.page;

import io.swagger.annotations.ApiModelProperty;
import java.util.Collection;
import java.util.List;

/**
 * @author : silver
 * @since : 2019-06-12 16:37
 */
public class PageWrapper<T> extends PageResult<T> {

	/**
	 * 每页的数量
	 */
	@ApiModelProperty(name = "pageSize", value = "每页的数量")
	private final int pageSize;

	/**
	 * 总页数
	 */
	@ApiModelProperty(name = "pages", value = "总页数")
	private int pages;

	public PageWrapper(T data) {
		PageDomain pageDomain = PageSupport.buildPageRequest();

		this.pageSize = pageDomain.getPageSize();
		super.data = data;

		if(data instanceof Collection){
			Collection<?> collection = (Collection<?>) data;
			super.setTotal(collection.size());
		}

		this.setPages(super.getTotal() % pageSize == 0 ? super.getTotal() / pageSize : super.getTotal() / pageSize + 1);
    }

    @SuppressWarnings("unchecked")
    public List<T> getPage(Integer queryPageNum) {
        int start = Math.min((queryPageNum - 1) * pageSize, (int) getTotal());
        long end = queryPageNum >= pages ? super.getTotal() : queryPageNum * pageSize;

        return ((List<T>) data).subList(start, (int) end);
    }

	public void setPages(Integer pages) {
		this.pages = pages;
	}
}
